// ElderDaoImpl.java
package com.community.dao.impl;
import com.community.dao.ElderDao;
import com.community.model.Elder;
import com.community.util.DBUtil;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ElderDaoImpl implements ElderDao {
    // 更新后的SQL语句
    private static final String INSERT_SQL =
            "INSERT INTO elders (name, age, gender, contact, family_contact, created_at) " +
                    "VALUES (?,?,?,?,?,?)";

    private static final String UPDATE_SQL =
            "UPDATE elders SET name=?, age=?, gender=?, contact=?, family_contact=? WHERE id=?";

    private static final String SELECT_BY_ID_SQL =
            "SELECT * FROM elders WHERE id=?";

    private static final String SELECT_ALL_SQL =
            "SELECT * FROM elders ORDER BY created_at DESC";

    private static final String SEARCH_BY_NAME_SQL =
            "SELECT * FROM elders WHERE name LIKE ?";
    //增加老人
    @Override
    public void insert(Elder elder) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(INSERT_SQL)) {
            pstmt.setString(1, elder.getName());
            pstmt.setInt(2, elder.getAge());
            pstmt.setString(3, elder.getGender());
            pstmt.setString(4, elder.getContact());
            pstmt.setString(5, elder.getFamilyContact());
            pstmt.setTimestamp(6,
                    Timestamp.valueOf(LocalDateTime.now()));  // 自动设置创建时间
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("添加老人信息失败", e);
        }
    }
//更新老人
    @Override
    public void update(Elder elder) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(UPDATE_SQL)) {
            pstmt.setString(1, elder.getName());
            pstmt.setInt(2, elder.getAge());
            pstmt.setString(3, elder.getGender());
            pstmt.setString(4, elder.getContact());
            pstmt.setString(5, elder.getFamilyContact());
            pstmt.setInt(6, elder.getId());

            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新老人信息失败", e);
        }
    }
    //删除老人
    @Override
    public void delete(int id) {
        String DELETE_SQL = "DELETE FROM elders WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(DELETE_SQL)) {
            pstmt.setInt(1, id);  // 设置第1个参数为ID
            int affectedRows = pstmt.executeUpdate();  // 执行删除操作

            if (affectedRows == 0) {
                throw new RuntimeException("老人ID " + id + " 不存在");
            }
        } catch (SQLException e) {
            throw new RuntimeException("删除elder失败", e);
        }    }
    //获取所有老人信息
    @Override
    public List<Elder> getAll() {
        List<Elder> elders = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(SELECT_ALL_SQL);
             ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                elders.add(mapRowToElder(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException("获取所有老人信息失败", e);
        }
        return elders;
    }
    @Override
    public Elder getById(int id) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(SELECT_BY_ID_SQL)) {
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            return rs.next() ? mapRowToElder(rs) : null;
        } catch (SQLException e) {
            throw new RuntimeException("获取老人信息失败", e);
        }
    }

    @Override
    public List<Elder> searchByName(String name) {
        List<Elder> results = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(SEARCH_BY_NAME_SQL)) {
            pstmt.setString(1, "%" + name + "%");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                results.add(mapRowToElder(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException("老人信息搜索失败", e);
        }
        return results;
    }

    // 更新后的映射方法
    private Elder mapRowToElder(ResultSet rs) throws SQLException {
        Elder elder = new Elder();
        elder.setId(rs.getInt("id"));
        elder.setName(rs.getString("name"));
        elder.setAge(rs.getInt("age"));
        elder.setGender(rs.getString("gender"));
        elder.setContact(rs.getString("contact"));
        elder.setFamilyContact(rs.getString("family_contact"));
        elder.setCreatedAt(
                rs.getTimestamp("created_at").toLocalDateTime()
        );
        return elder;
    }
}